// 用户状态管理
import { ref, reactive } from 'vue'
import { login as apiLogin, logout as apiLogout, getCurrentUserInfo } from '@/api/auth'

// 用户信息
export const userInfo = ref({
  userId: null,
  username: '',
  status: '',
  lastLoginTime: null,
  roles: []
})

// 用户菜单权限
export const userMenus = ref([])

// 登录状态
export const isLoggedIn = ref(false)

// 当前用户角色
export const currentRole = ref('')

/**
 * 登录
 */
export const login = async (loginData) => {
  try {
    console.log('调用后端登录API...')
    const response = await apiLogin(loginData)
    console.log('后端登录响应:', response)
    
    // 处理标准API响应格式 { flag: true, data: { accessToken, userInfo }, message }
    if (response.flag === true && response.data) {
      const loginResult = response.data
      
      // 存储token
      const token = loginResult.accessToken || loginResult.token
      if (token) {
        localStorage.setItem('token', token)
        localStorage.setItem('refreshToken', loginResult.refreshToken || '')
        
        // 设置用户信息
        if (loginResult.userInfo) {
          userInfo.value = loginResult.userInfo
          localStorage.setItem('username', loginResult.userInfo.username)
          
          // 设置用户角色
          if (loginResult.userInfo.roles && loginResult.userInfo.roles.length > 0) {
            const role = loginResult.userInfo.roles[0]
            currentRole.value = role.roleKey
            localStorage.setItem('userRole', role.roleKey)
          }
        }
        
        // 设置菜单权限
        if (loginResult.menus) {
          userMenus.value = loginResult.menus
          localStorage.setItem('userMenus', JSON.stringify(loginResult.menus))
        }
        
        isLoggedIn.value = true
        return loginResult
      } else {
        throw new Error('后端返回数据中没有token')
      }
    } else {
      throw new Error(`登录失败: ${response.message || '未知错误'}`)
    }
    
  } catch (error) {
    console.error('登录失败:', error)
    throw error
  }
}

/**
 * 模拟登录（开发时使用）
 */
const mockLogin = (loginData) => {
  const { username, password } = loginData
  
  // 模拟用户数据
  const mockUsers = {
    'admin': {
      userId: 1,
      username: 'admin',
      status: '1',
      roles: [{ roleKey: 'admin', roleName: '超级管理员' }]
    },
    'medical_admin': {
      userId: 2,
      username: 'medical_admin',
      status: '1',
      roles: [{ roleKey: 'medical_info_admin', roleName: '医保信息维护员' }]
    },
    'doctor_001': {
      userId: 3,
      username: 'doctor_001',
      status: '1',
      roles: [{ roleKey: 'hospital_doctor', roleName: '医院医生' }]
    },
    'insurance_admin': {
      userId: 4,
      username: 'insurance_admin',
      status: '1',
      roles: [{ roleKey: 'insurance_center_admin', roleName: '医保中心管理员' }]
    }
  }
  
  const user = mockUsers[username]
  if (!user || password !== '123456') {
    throw new Error('用户名或密码错误')
  }
  
  // 生成模拟token
  const mockToken = 'mock_token_' + Date.now()
  
  // 存储登录信息
  localStorage.setItem('token', mockToken)
  localStorage.setItem('username', user.username)
  localStorage.setItem('userRole', user.roles[0].roleKey)
  
  // 设置状态
  userInfo.value = user
  currentRole.value = user.roles[0].roleKey
  isLoggedIn.value = true
  
  console.log('模拟登录成功:', user)
  
  return {
    accessToken: mockToken,
    userInfo: user,
    menus: []
  }
}

/**
 * 登出
 */
export const logout = async () => {
  try {
    await apiLogout()
  } catch (error) {
    console.error('登出请求失败:', error.message)
  } finally {
    // 清除本地存储
    localStorage.clear()
    
    // 重置状态
    userInfo.value = {
      userId: null,
      username: '',
      status: '',
      lastLoginTime: null,
      roles: []
    }
    userMenus.value = []
    currentRole.value = ''
    isLoggedIn.value = false
  }
}

/**
 * 获取用户信息
 */
export const fetchUserInfo = async () => {
  try {
    const response = await getCurrentUserInfo()
    userInfo.value = response
    
    if (response.roles && response.roles.length > 0) {
      const role = response.roles[0]
      currentRole.value = role.roleKey
      localStorage.setItem('userRole', role.roleKey)
    }
    
    return response
  } catch (error) {
    console.error('获取用户信息失败:', error.message)
    throw error
  }
}

/**
 * 初始化用户状态（从本地存储恢复）
 */
export const initUserState = () => {
  const token = localStorage.getItem('token')
  const username = localStorage.getItem('username')
  const userRole = localStorage.getItem('userRole')
  const storedUserMenus = localStorage.getItem('userMenus')
  
  if (token && username) {
    isLoggedIn.value = true
    userInfo.value.username = username
    currentRole.value = userRole || ''
    
    if (storedUserMenus) {
      try {
        userMenus.value = JSON.parse(storedUserMenus)
      } catch (error) {
        console.error('解析用户菜单失败:', error)
      }
    }
  }
}

/**
 * 检查是否有权限访问指定路由
 */
export const hasRoutePermission = (routePath) => {
  if (!currentRole.value) return false
  
  const routePermissions = {
    'admin': ['medical-info', 'hospital-doctor', 'insurance-center', 'system'],
    'medical_info_admin': ['medical-info', 'system'],
    'hospital_doctor': ['hospital-doctor'],
    'insurance_center_admin': ['insurance-center', 'system'],
  }
  
  const allowedRoutes = routePermissions[currentRole.value] || []
  const routeModule = routePath.split('/')[1]
  
  return allowedRoutes.includes(routeModule)
}
